package com.itcast.donkey.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.itcast.donkey.R;
import com.itcast.donkey.adapters.Detailed_Travel_Area_Adapter;
import com.itcast.donkey.adapters.GridViewImageHotleAdapter;
import com.itcast.donkey.adapters.GridViewImageTuiJianAdapter;
import com.itcast.donkey.modles.DetailedTravel_area_Modles;
import com.itcast.donkey.modles.ScrollViewRecyclerView;
import com.itcast.donkey.modles.UriModles;
import com.squareup.picasso.Picasso;

import java.io.IOException;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 详细的旅行地的界面
 * Created by lanouhn on 16/8/30.
 */
public class Detailed_Travel_area_Activity extends AppCompatActivity implements View.OnClickListener {
    private DetailedTravel_area_Modles modles;

    private ImageView ivDetailedTravelArea;
    private LinearLayout linScenicSpot;

    private LinearLayout lin_photo, lin_journey, lin_map;
    private ImageView ivImage;
    private TextView tvDetailedTravelAreaName;
    private TextView tvDetailedTravelAreaEnglish;
    private LinearLayout lin1DetailedTravelArea;
    private TextView tvDetailedTravelPhotoCount;
    private TextView tvDetailedTravelJourney;
    private TextView tvDetailedTravelMap;
    private TextView tvDetailedTravelTitle;
    private ScrollViewRecyclerView recyclerDetailedTravelArea;

    //标题栏
    private ImageView backScenicApot;
    private ImageView ivChanScenicSpot;
    private ImageView ivStarJourney;
    private ImageView ivShareJourney;

    //点击是否收藏
    private boolean isCollect = true;

    //适配器
    private Detailed_Travel_Area_Adapter adapter;
    //最下方的推荐
    private TextView tv_att_title;
    private TextView tv_hotles_title;
    private HorizontalScrollView horShowContent;
    private GridView gridImageShowContent;
    private LinearLayout linTextviewName;
    private HorizontalScrollView horShowJourneyContent;
    private GridView gridImageJourneyShowContent;
    private LinearLayout linTextviewJourneyName;

    private int id;
    private int mapId;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detailed_travel_area);
        initView();
        initData();
        initEvent();
    }

    private void initView() {

        //背景图片
        ivDetailedTravelArea = (ImageView) findViewById(R.id.iv_detailed_travel_area);
        linScenicSpot = (LinearLayout) findViewById(R.id.lin_scenic_spot);
        backScenicApot = (ImageView) findViewById(R.id.back_scenic_apot);
        ivChanScenicSpot = (ImageView) findViewById(R.id.iv_chan_scenic_spot);
        ivStarJourney = (ImageView) findViewById(R.id.iv_star_journey);
        ivShareJourney = (ImageView) findViewById(R.id.iv_share_journey);
        ivImage = (ImageView) findViewById(R.id.iv_image);
        tvDetailedTravelAreaName = (TextView) findViewById(R.id.tv_detailed_travel_area_name);
        tvDetailedTravelAreaEnglish = (TextView) findViewById(R.id.tv_detailed_travel_area_english);
        lin1DetailedTravelArea = (LinearLayout) findViewById(R.id.lin1_detailed_travel_area);
        tvDetailedTravelPhotoCount = (TextView) findViewById(R.id.tv_detailed_travel_photo_count);
        tvDetailedTravelJourney = (TextView) findViewById(R.id.tv_detailed_travel_journey);
        tvDetailedTravelMap = (TextView) findViewById(R.id.tv_detailed_travel_map);
        tvDetailedTravelTitle = (TextView) findViewById(R.id.tv_detailed_travel_title);
        recyclerDetailedTravelArea = (ScrollViewRecyclerView) findViewById(R.id.recycler_detailed_travel_area);

        //三个可点击的图片
        lin_photo = (LinearLayout) findViewById(R.id.line_detailed_travel_photo);
        lin_journey = (LinearLayout) findViewById(R.id.line_detailed_travel_journey);
        lin_map = (LinearLayout) findViewById(R.id.line_detailed_travel_map);

        //最下方的横向滑动的图片
        horShowContent = (HorizontalScrollView) findViewById(R.id.hor_show_content);
        gridImageShowContent = (GridView) findViewById(R.id.lin_image_show_content);
        horShowJourneyContent = (HorizontalScrollView) findViewById(R.id.hor_show_journey_content);
        gridImageJourneyShowContent = (GridView) findViewById(R.id.lin_image_journey_show_content);

        tv_att_title = (TextView) findViewById(R.id.tv_attractions_title);
        tv_hotles_title = (TextView) findViewById(R.id.tv_hotels_title);

    }

    private void initData() {
        Intent intent = getIntent();
        id = intent.getIntExtra("id", 0);
        mapId = intent.getIntExtra("mapId", mapId);
        final String url = UriModles.ATTACK_CLICK_FRONT_DETAILED_TRAVEL_AREA_URL + id + UriModles.ATTACK_CLICK_END_DETAILED_TRAVEL_AREA_URL;

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        handler.sendEmptyMessage(0);
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String values = response.body().string();
                        Gson gson = new Gson();
                        modles = gson.fromJson(values, DetailedTravel_area_Modles.class);
                        if (modles.getAttraction_trip_tags().size() > 0) {
                            handler.sendEmptyMessage(1);
                        } else {
                            handler.sendEmptyMessage(2);
                        }
                    }
                });
            }
        }).start();
    }

    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    Picasso.with(Detailed_Travel_area_Activity.this).load(modles.getImage_url()).into(ivDetailedTravelArea);
                    tvDetailedTravelPhotoCount.setText("图片" + modles.getPhotos_count());
                    tvDetailedTravelJourney.setText("游记" + modles.getAttraction_trips_count());
                    tvDetailedTravelMap.setText("地图");
                    tvDetailedTravelTitle.setText(modles.getDescription());
                    tvDetailedTravelAreaName.setText(modles.getName_zh_cn());
                    tvDetailedTravelAreaEnglish.setText(modles.getName_en());

                    if (!modles.getAttractions().isEmpty()) {
                        horShowContent.setVisibility(View.VISIBLE);
                        tv_att_title.setVisibility(View.VISIBLE);
                        tv_att_title.setText("附近的旅行地" + modles.getAttractions().size());

                        int size = modles.getAttractions().size();
                        int length = 100;
                        DisplayMetrics dm = new DisplayMetrics();
                        getWindowManager().getDefaultDisplay().getMetrics(dm);
                        float density = dm.density;
                        int gridviewWidth = (int) (size * (length + 4) * density);
                        int itemWidth = (int) (length * density);

                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
                        gridImageShowContent.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
                        gridImageShowContent.setColumnWidth(itemWidth); // 设置列表项宽
                        gridImageShowContent.setHorizontalSpacing(5); // 设置列表项水平间距
                        gridImageShowContent.setStretchMode(GridView.NO_STRETCH);
                        gridImageShowContent.setNumColumns(size); // 设置列数量=列表集合数

                        GridViewImageTuiJianAdapter adapter = new GridViewImageTuiJianAdapter(Detailed_Travel_area_Activity.this, modles.getAttractions());
                        gridImageShowContent.setAdapter(adapter);

                        gridImageShowContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Intent intent = new Intent(Detailed_Travel_area_Activity.this, Detailed_Travel_area_Activity.class);
                                intent.putExtra("id", modles.getAttractions().get(position).getId());
                                startActivity(intent);
                                finish();
                            }
                        });
                    }
                    if (!modles.getHotels().isEmpty()) {
                        horShowJourneyContent.setVisibility(View.VISIBLE);
                        tv_hotles_title.setVisibility(View.VISIBLE);
                        tv_hotles_title.setText("附近酒店" + modles.getHotels().size());
                        int size = modles.getAttractions().size();
                        int length = 100;
                        DisplayMetrics dm = new DisplayMetrics();
                        getWindowManager().getDefaultDisplay().getMetrics(dm);
                        float density = dm.density;
                        int gridviewWidth = (int) (size * (length + 4) * density);
                        int itemWidth = (int) (length * density);

                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
                        gridImageJourneyShowContent.setLayoutParams(params); // 设置GirdView布局参数,横向布局的关键
                        gridImageJourneyShowContent.setColumnWidth(itemWidth); // 设置列表项宽
                        gridImageJourneyShowContent.setHorizontalSpacing(5); // 设置列表项水平间距
                        gridImageJourneyShowContent.setStretchMode(GridView.NO_STRETCH);
                        gridImageJourneyShowContent.setNumColumns(size); // 设置列数量=列表集合数


                        GridViewImageHotleAdapter adapter = new GridViewImageHotleAdapter(Detailed_Travel_area_Activity.this, modles.getHotels());
                        gridImageJourneyShowContent.setAdapter(adapter);

                        gridImageJourneyShowContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                Uri uri = Uri.parse(UriModles.ATTACK_HOTLE_URL + modles.getHotels().get(position).getId());
                                Intent intent = new Intent();
                                intent.setData(uri);
                                intent.setAction(Intent.ACTION_VIEW);
                                startActivity(intent);

                            }
                        });
                    }
                    adapter = new Detailed_Travel_Area_Adapter(Detailed_Travel_area_Activity.this, modles);
                    recyclerDetailedTravelArea.setAdapter(adapter);
                    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(Detailed_Travel_area_Activity.this);
                    linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
                    recyclerDetailedTravelArea.setLayoutManager(linearLayoutManager);

                    break;
                case 2:
                    break;
            }
        }
    };

    private void initEvent() {
        //标题栏的点击事件
        backScenicApot.setOnClickListener(this);
        ivChanScenicSpot.setOnClickListener(this);
        ivStarJourney.setOnClickListener(this);
        ivShareJourney.setOnClickListener(this);

        //图片，游记和地图的点击事件
        lin_photo.setOnClickListener(this);
        lin_journey.setOnClickListener(this);
        lin_map.setOnClickListener(this);


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //返回按钮
            case R.id.back_scenic_apot:
            case R.id.iv_chan_scenic_spot:
                finish();
                break;
            //星星按钮
            case R.id.iv_star_journey:
                if (isCollect) {
                    ivStarJourney.setBackgroundResource(R.mipmap.star_24_white_full);
                    isCollect = false;
                    Toast.makeText(this, "已收藏", Toast.LENGTH_SHORT).show();
                } else {
                    ivStarJourney.setBackgroundResource(R.mipmap.star_24_white_empty);
                    Toast.makeText(this, "已取消", Toast.LENGTH_SHORT).show();
                    isCollect = true;
                }
                break;
            //分享
            case R.id.iv_share_journey:
                showShare();
                break;
            case R.id.line_detailed_travel_photo:
                Intent intent2 = new Intent(Detailed_Travel_area_Activity.this, ClickPhotoActivity.class);
                intent2.putExtra("id", modles.getId());
                intent2.putExtra("name", modles.getName_zh_cn());
                startActivity(intent2);
                break;
            case R.id.line_detailed_travel_journey:
                Intent intent = new Intent(Detailed_Travel_area_Activity.this, ClickJourneyActivity.class);
                intent.putExtra("id", modles.getId());
                intent.putExtra("count", modles.getAttraction_trips_count());
                intent.putExtra("name", modles.getName_zh_cn());
                startActivity(intent);
                break;
            case R.id.line_detailed_travel_map:
                Intent intent1 = new Intent(Detailed_Travel_area_Activity.this, ToolMapActivity.class);
                intent1.putExtra("id", mapId);
                startActivity(intent1);
                break;
        }
    }


    //分享
    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("QQ空间分享测试");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");

// 启动分享GUI
        oks.show(this);
    }
}
